#include "ChatServer.h"
#include "../ConfigMgr.h"
#include "../log.h"
#include "../Singleton.h"
#include "../AsioIoContextPool.h"
#include "../DB/MySql/MySqlConPool.h"
#include "../GrpcClient/StatusGrpcClient.h"


uint16_t GetGateServerPort(std::shared_ptr<Config> const& config, const std::string& serverName)
{
    if(serverName == "GateServer_01")
    {
        return config->GateServerInfo_01.Port;
    }
    else if(serverName == "GateServer_02")
    {
        return config->GateServerInfo_02.Port;
    }
    
    return 0;
}

int main(int argc, char* argv[])
{
    //检查必须有一个参数，表示所用的服务器名称
    if(argc < 2)
    {
        log_error("Usage: {} ServerName", argv[0]);
        log_info("Example: ./ChatServer GateServer_01");
        return -1;
    }

    //设置日志级别
	set_log_level(log_level::trace);

    auto config = ConfigMgr::GetConfig();

    uint16_t port = GetGateServerPort(config, argv[1]);
    if(port == 0)
    {
        log_error("GateServerPort failed, ServerName: {}", argv[1]);
        return -2;
    }

    //初始化MySQL连接池，并显示
    Singleton<MySqlPool>::GetInstance()->show();

    //初始化Status gRPC 客户端
    Singleton<StatusGrpcClient>::GetInstance();

    try
    {
        auto pool = Singleton<AsioIoContextPool>::GetInstance();
        boost::asio::io_context ioc;
        boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
        signals.async_wait([&](boost::system::error_code error, int si)
            {
                if(error)
                {
                    log_error("main signal error: {}", error.message());
                    return;
                }
                log_info("Signal {} received, stopping...", si);

                // 停止IO上下文
                ioc.stop();
                // 停止线程池
                pool->Stop();
            });
        
        Server server(ioc, port);
        ioc.run();
    }
    catch (const std::exception& e)
    {
        log_error("main exception: {}", e.what());
        return -3;
    }

    return 0;
}